import pandas as pd
import re
import os

# 假设日志数据保存在一个文本文件中，文件名为log.txt
log_file = 'log.txt'

# 读取日志文件
with open(log_file, 'r', encoding='utf-8') as file:
    log_data = file.readlines()

# 定义用于匹配测试项目和结果的正则表达式
test_suite_pattern = re.compile(r'\[\d+/\d+ done\]: (\S+).*')
test_result_pattern_ok = re.compile(r'\[ok\]: (.+) \((\d+ ms)\)')
test_result_pattern_ignore = re.compile(r'\[ignore\]: (.+)')

# 用于存储测试数据
test_suites = {}
current_suite = None

# 解析日志数据
for line in log_data:
    suite_match = test_suite_pattern.match(line)
    result_match_ok = test_result_pattern_ok.match(line)
    result_match_ignore = test_result_pattern_ignore.match(line)

    if suite_match:
        current_suite = suite_match.group(1)
        if current_suite not in test_suites:
            test_suites[current_suite] = []
    elif result_match_ok and current_suite:
        test_name = result_match_ok.group(1)
        test_time = result_match_ok.group(2)
        test_suites[current_suite].append(f"{test_name} ({test_time})")
    elif result_match_ignore and current_suite:
        test_name = result_match_ignore.group(1)
        test_suites[current_suite].append(f"{test_name} (ignored)")

# 将解析后的数据转换为表格
table_data = []

for suite, results in test_suites.items():
    combined_results = "; ".join(results)
    table_data.append([suite, combined_results])

# 使用Pandas创建数据框
df = pd.DataFrame(table_data, columns=['Test Suite', 'Test Results'])

# 显示表格
print(df)

# 获取当前用户的桌面路径
desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

# 使用不同的保存路径以避免权限问题
output_file = os.path.join(desktop_path, 'test_results_combined_new.csv')

try:
    df.to_csv(output_file, index=False)
    print(f"CSV file saved successfully to {output_file}")
except PermissionError:
    print(f"Permission denied: {output_file}")
    # 尝试保存到其他目录
    alternative_path = os.path.join(os.getcwd(), 'test_results_combined.csv')
    df.to_csv(alternative_path, index=False)
    print(f"CSV file saved successfully to {alternative_path}")
